package controller.user;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.UserDTO;
import bizlogic.UserManager;

public class ProcessUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ProcessUserServlet() {
        super();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) {
				
		UserManager um = new UserManager();
		RequestDispatcher rd;

		if(isUserInfosCorrect(request)){
			
			UserDTO user = new UserDTO();
			user.setUsername(request.getParameter("username").trim());
			user.setEmail(request.getParameter("email").trim());
			user.setName(request.getParameter("name").trim());
			user.setType(request.getParameter("role").trim());
			user.setManager(request.getParameter("managerInfos").trim());
			user.setStatus(Integer.parseInt(request.getParameter("status")));
			user.setPassword(request.getParameter("password").trim()); 
			
			String ins = (String) request.getParameter("ins");			
			if (ins.equalsIgnoreCase("true")) {
				um.createUser(user);
			} else {
				um.updateUser(user);
			}
			
			try {
				response.sendRedirect("/FBS/LoadStaff");
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} else{

			request.setAttribute("errormessage", "WARNING: Invalid inputs");
			rd = request.getRequestDispatcher("/LoadStaff");
				try {
					rd.include(request, response);
				} catch (ServletException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}	
	}
	
	private boolean isUserInfosCorrect(HttpServletRequest request){
		
		boolean result = false;
				
		if(request.getParameter("username").trim().isEmpty()){
			return result;
		}
		
		if(request.getParameter("name").trim().isEmpty()){
			return result;
		}
		
		if(request.getParameter("email").trim().isEmpty()){
			return result;
		}
		
		if(request.getParameter("password").trim().isEmpty()){
			return result;
		}
		
		if(request.getParameter("status") == null){
			return result;
		}
		
		result = true;
		return result;
	}
}